import { Button, Form, Input, Modal, Select } from 'antd'
import { EditOutlined } from '@ant-design/icons'
import axios from 'axios'
import React, { useEffect, useState } from 'react'
import PubSub from 'pubsub-js'
const { Option } = Select

interface Values {
  title: string
  description: string
  modifier: string
}

interface CollectionCreateFormProps {
  visible: boolean
  onCreate: (values: Values) => void
  onCancel: () => void
}
interface IRegion {
  id: number
  title: string
  value: string
}
interface IRole {
  id: number
  roleName: string
  roleType: number
  rights: string[]
}
const CollectionCreateForm: React.FC<CollectionCreateFormProps & ICurrentUser> = ({ visible, onCreate, onCancel, currentUser }) => {
  const [regionList, setregionList] = useState<IRegion[]>([])
  const [roleList, setroleList] = useState<IRole[]>([])
  const [currentRole, setcurrentRole] = useState<number>(0)
  useEffect(() => {
    if (regionList.length === 0) {
      axios.get('/regions').then(({ data }) => setregionList(data))
    }
    if (roleList.length === 0) {
      axios.get('/roles').then(({ data }) => setroleList(data))
    }
    form.setFieldsValue(currentUser)
    setcurrentRole(currentUser.roleId)
  }, [visible])

  const [form] = Form.useForm()
  const {roleId, region} = JSON.parse((localStorage.getItem('token') as string))
  return (
    <Modal
      forceRender
      visible={visible}
      title="Create a new collection"
      okText="Create"
      cancelText="Cancel"
      onCancel={onCancel}
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            form.resetFields()
            onCreate(values)
          })
          .catch((info) => {
            console.log('Validate Failed:', info)
          })
      }}
    >
      <Form form={form} layout="vertical" name="form_in_modal" initialValues={{ modifier: 'public' }}>
        <Form.Item name="username" label="用户名" rules={[{ required: true, message: 'Please input the username of collection!' }]}>
          <Input />
        </Form.Item>
        <Form.Item name="password" label="密码" rules={[{ required: true, message: 'Please input the password of collection!' }]}>
          <Input />
        </Form.Item>
        <Form.Item name="region" label="区域" rules={currentRole === 1 ? [] : [{ required: true, message: 'Please input the region of collection!' }]}>
          <Select placeholder="Select a area" disabled={currentRole === 1}>
            {regionList.map((item) => (
              <Option key={item.id} value={item.value} disabled={roleId !== 1} >
                {item.title}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="roleId" label="角色" rules={[{ required: true, message: 'Please input the role of collection!' }]}>
          <Select
            placeholder="Select a role"
            onChange={(value) => {
              setcurrentRole(value)
              if (value === 1) {
                form.setFieldValue('region', '')
              }
            }}
          >
            {roleList.map((item) => (
              <Option key={item.id} value={item.id} disabled={roleId !== 1}>
                {item.roleName}
              </Option>
            ))}
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  )
}
interface IUser {
  id: number
  username: string
  password: string | number
  roleState: boolean
  default: boolean
  region: string
  roleId: number
  role: IRole[]
}
interface IProps {
  disabled: boolean
  currentUser: IUser
}
interface ICurrentUser {
  currentUser: IUser
}
const App: React.FC<IProps> = (props) => {
  const [visible, setVisible] = useState(false)

  const onCreate = (values: any) => {
    setVisible(false)
    axios.patch(`/users/${props.currentUser.id}`, values).then(() => PubSub.publish('updUserList'))
  }

  return (
    <div>
      <Button
        type="primary"
        shape="circle"
        disabled={props.disabled}
        icon={<EditOutlined />}
        onClick={() => {
          setVisible(true)
        }}
      ></Button>
      <CollectionCreateForm
        visible={visible}
        onCreate={onCreate}
        onCancel={() => {
          setVisible(false)
        }}
        currentUser={props.currentUser}
      />
    </div>
  )
}

export default App
